package gui;

import entities.Artist;
import entities.MusicGroup;
import helpers.UIHelper;
import helpers.ValidationHelper;
import java.util.ArrayList;


// Διάλογος Διαχείρισης Συγκροτήματος
public class MusicGroupForm extends javax.swing.JDialog {
    private String dialogResult = "Cancel";
    private final ValidationHelper validator = new ValidationHelper();

    
    public MusicGroupForm(MusicGroup _entity) {
        initComponents();
        
        // Εμφάνισε το παράθυρο σαν modal και σε κέντρο σε σχέση με την parent form
        this.setModal(true);
        this.setLocationRelativeTo(this.getOwner());
        
        entity = _entity;
        
        updateControlsFromEntity();
    }
    
    // Constructor χωρίς ορίσματα που κάνει κλήση του παραπάνω constructor
    // με όρισμα νέο αντικείμενο
    public MusicGroupForm() {
        this(new MusicGroup());
    }
    
    // Ενημέρωση των των controls από τα properties του entity
    private void updateControlsFromEntity(){
        // Αν το id του entity δεν είναι null, το αντικείμενο είναι persisted
        // οπότε αρχικοποιούμε τις τιμές των controls
        if (entity.getId() != null) {
            if (entity.getArtistList() == null) {
                entity.setArtistList(new ArrayList<Artist>());
            }
            this.nameTextField.setText(entity.getName());
            this.creationDateTextField.setText(validator.getDF().format(entity.getFormationDate()));

            artistList.clear();
            artistList.addAll(entity.getArtistList());
        }
    }
    
    // Ενημέρωση των properties του entity από τις τιμές των controls
    private void updateEntityFromControls() {
        entity.setName(nameTextField.getText());
        
        if (validator.isValidDate(creationDateTextField.getText())){
            entity.setFormationDate(validator.parseDate(creationDateTextField.getText()));
        }
        
        entity.setArtistList(artistList);
    }
    
    // Επιστρέφει το entity της φόρμας
    public MusicGroup getEntity()
    {
        updateEntityFromControls();
        return entity;
    }
    
    // Επιστρέφει την τρέχουσα τιμή του dialogResult (Save/Cancel)
    public String getDialogResult()
    {
        return this.dialogResult;
    }
    
    // Κλείνει το διάλογο αφού πρώτα κάνει τους απαραίτητους ελέγχους
    protected void closeDialog(String _dialogResult) {
        if (_dialogResult != null && !_dialogResult.isEmpty()){
            dialogResult = _dialogResult;
        }
        if ((this.dialogResult.equals("Save") && validateEntity()) || this.dialogResult.equals("Cancel")){
            this.dispose();
        }
    }
    
    // Έλεγχος εγκυρότητας δεδομένων πριν την αποθήκευση
    // με χρήση ενός managers.ValidationHelper
    protected boolean validateEntity(){
        validator.getRules().clear();
        validator.addRule(artistList.size() < 2, "Το Συγκρότημα πρέπει να αποτελείται απο τουλάχιστον 2 καλλιτέχνες !");
        validator.addDateRule(this.creationDateTextField.getText());
        
        return validator.validateRules(this);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entity = new entities.MusicGroup();
        em = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("KLMRadioStationPU").createEntityManager();
        allArtistQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT a FROM Artist a");
        allArtistList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(allArtistQuery.getResultList());
        artistQuery1 = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT a FROM Artist a where a.id = -1");
        artistList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(new java.util.LinkedList(artistQuery1.getResultList()));
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        artistsListBox = new javax.swing.JList();
        jLabel3 = new javax.swing.JLabel();
        nameTextField = new javax.swing.JTextField();
        creationDateTextField = new javax.swing.JFormattedTextField();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        addArtistButton = new javax.swing.JButton();
        deleteArtistButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Διαχείριση Συγκροτήματος");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setText("Επωνυμία Συγκροτήματος");

        jLabel2.setText("Ημερομηνία Δημιουργίας");

        artistsListBox.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, artistList, artistsListBox);
        bindingGroup.addBinding(jListBinding);

        jScrollPane1.setViewportView(artistsListBox);

        jLabel3.setText("Λίστα Καλλιτεχνών");

        creationDateTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/MM/yyyy"))));

        saveButton.setText("Αποθήκευση");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Άκυρο");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        addArtistButton.setText("Εισαγωγή Καλλιτέχνη");
        addArtistButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addArtistButtonActionPerformed(evt);
            }
        });

        deleteArtistButton.setText("Διαγραφή Καλλιτέχνη");
        deleteArtistButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteArtistButtonActionPerformed(evt);
            }
        });

        table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, allArtistList, table);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artisticName}"));
        columnBinding.setColumnName("Καλλιτεχνικό Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${firstName}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${lastName}"));
        columnBinding.setColumnName("Επίθετο");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane2.setViewportView(table);

        jLabel4.setText("Διαθέσιμοι Καλλιτέχνες");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(saveButton)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3))
                                .addComponent(addArtistButton, javax.swing.GroupLayout.Alignment.LEADING))
                            .addGap(18, 18, 18)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(creationDateTextField)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE)
                                .addComponent(deleteArtistButton)
                                .addComponent(nameTextField))))
                    .addComponent(jLabel4))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(creationDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(addArtistButton)
                    .addComponent(deleteArtistButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 236, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(saveButton))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        closeDialog("Save");
    }//GEN-LAST:event_saveButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        closeDialog("Cancel");
    }//GEN-LAST:event_cancelButtonActionPerformed

    //delete artist from list
    private void deleteArtistButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteArtistButtonActionPerformed
        Artist artist = (Artist)artistsListBox.getSelectedValue();
        artistList.remove(artist);
    }//GEN-LAST:event_deleteArtistButtonActionPerformed

    private void addArtistButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addArtistButtonActionPerformed
        Artist artist = allArtistList.get(table.getSelectedRow());
        if(artistList.contains(artist))
        {
            UIHelper.showWarning(this, "Διαχείριση Δεδομένων", "Ο επιλεγμένος καλλιτέχνης ανήκει ήδη στο συγκρότημα !");
        }
        else
        {
            artistList.add(artist);
        }
    }//GEN-LAST:event_addArtistButtonActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        closeDialog("Cancel");
    }//GEN-LAST:event_formWindowClosing

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addArtistButton;
    private java.util.List<entities.Artist> allArtistList;
    private javax.persistence.Query allArtistQuery;
    private java.util.List<entities.Artist> artistList;
    private javax.persistence.Query artistQuery1;
    private javax.swing.JList artistsListBox;
    private javax.swing.JButton cancelButton;
    private javax.swing.JFormattedTextField creationDateTextField;
    private javax.swing.JButton deleteArtistButton;
    private javax.persistence.EntityManager em;
    private entities.MusicGroup entity;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JButton saveButton;
    private javax.swing.JTable table;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
